/**
 * @author lk
 * @date 2022/6/6 9:58
 */
package com.mmall.thread;

public class BlockTest {
    private static StringBuffer sb1 = new StringBuffer();
    private static StringBuffer sb2 = new StringBuffer();

    private static void work1() {
        synchronized (sb1) {
            sb1.append(1);
            sb2.append("a");
            sleep();
            synchronized (sb2) {
                sb1.append(2);
                sb2.append("b");
            }
        }
        System.out.println(sb1);
        System.out.println(sb2);
    }

    static void work2() {
        synchronized (sb2) {
            sleep();
            sb1.append(3);
            sb2.append("c");
            synchronized (sb1) {
                sb1.append(4);
                sb2.append("d");
            }
        }
        System.out.println(sb1);
        System.out.println(sb2);
    }

    static void sleep() {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Thread t1 = new Thread(BlockTest::work1);
        Thread t2 = new Thread(BlockTest::work2);
        t1.start();
        t2.start();
        Runtime.getRuntime().addShutdownHook(new Thread(()-> System.out.println("shutdown!")));
    }
}
